from django.shortcuts import render
from django.http import HttpResponse , JsonResponse
from .. models import Users
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Q

from django.contrib.auth.decorators import permission_required

# Create your views here.

# 后台首页
@permission_required('myadmin.show_users',raise_exception = True)
def adminindex(request):

	return render(request,'admin/index.html')


# 登陆页面
def login(request):
	# 如果访问当前页面的请求方式为GET，则返回一个登陆界面
	if request.method == 'GET':
		return render(request,'admin/login.html')
	elif request.method == 'POST':
		# 执行登录
		print('1111',request.POST['username'])
		# 判断验证码是否正确
		if request.POST['vcode'].lower() != request.session['verifycode'].lower():
			return HttpResponse('<script>alert("验证码错误");location.href="/admin/login";</script>')
		# 判断用户名和密码
		obj = Users.objects.filter(username=request.POST['username'])
		if obj:
			obj = obj[0]
			# 判断密码
			if check_password(request.POST['password'],obj.password):
				# 密码正确
				# 判断是否为管理员
				if obj.status == 3:
					# 有权限
					# 进行登陆
					# 添加session 中间件限制登陆时使用
					request.session['AdminUser'] = {'name':obj.username,'pic':obj.picurl}
					return HttpResponse('<script>alert("登录成功");location.href="/admin";</script>')

		return HttpResponse('<script>alert("用户名或密码不存在");location.href="/admin/login";</script>')



# 后台退出登录
def logout(request):

	del request.session['AdminUser']
	return HttpResponse('<script>alert("退出登录成功");location.href="/admin/login";</script>')



# ajax 文件上传
def ajaxupload(request):

	import time,random
	src = request.POST.get('src',None)
	myfile = request.FILES.get('pic',None)
	# 判断是有文件上传
	if not myfile:
		return JsonResponse({'code':1,'msg':'没有文件上传'})

	# 执行文件上传
	# 自定义文件名 时间戳 + 随机数 +.jpg
	filename = str(time.time())+str(random.randrange(10000,99999))
	# 获取当前撒谎给你传文件的后缀名
	hzm = myfile.name.split('.').pop()
	# 允许上传的文件类型
	arrlist = ['png','jpg','jpeg','bmp','ico','gif']
	# 如果上传的文件类型不正确
	if hzm not in arrlist:
		return JsonResponse({'code':2,'msg':'上传的文件类型错误'})

	# 打开文件
	file = open('./static/pics/tmp/'+filename+'.'+hzm,'wb+')
	# 分块写入文件
	for chunk in myfile.chunks():
		file.write(chunk)
	# 关闭文件
	file.close()
	# 返回文件的url路径
	return JsonResponse({'code':0,'msg':'上传成功','url':'/static/pics/tmp/'+filename+'.'+hzm})


	return HttpResponse('ajaxupload')





# 转到用户添加页面
@permission_required('myadmin.insert_users',raise_exception = True)
def useradd(request):
	return render(request,'admin/user/add.html')

# 执行用户添加
@permission_required('myadmin.insert_users',raise_exception = True)
def userinsert(request):
	# return HttpResponse('userinsert')
	pic = upload(request)
	if not pic:
		return HttpResponse('<script>alert("上传文件类型不正确，只能上传图片类型");location.href="/admin/user/add"</script>')

	try:
		obj = Users()
		obj.username = request.POST.get('username')
		obj.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
		obj.email = request.POST.get('email')
		obj.phone = request.POST.get('phone')
		obj.age = request.POST.get('age')
		obj.sex = request.POST.get('sex')
		obj.picurl = pic
		obj.save()
		return HttpResponse('<script>alert("添加成功");location.href="/admin/user/list"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/user/add"</script>')


# 转到列表页面
@permission_required('myadmin.show_users',raise_exception = True)
def userlist(request):
	# 清除ajax上传的文件
	import os
	for i in os.listdir('.'+'/static/pics/tmp'):
		os.remove('.'+'/static/pics/tmp/'+i)


	# 获取搜索条件
	types = request.GET.get('types',None)
	# 获取搜索关键字
	keywords = request.GET.get('keywords','')

	statuslist = {'正常':0,'禁止':1,'管理员':3}
	# 判断是否由搜索条件
	if types :
		# 有搜索条件，按条件搜索
		if types == 'all':
			data = Users.objects.filter(Q(status__contains=keywords)|Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains=keywords)|Q(addtime__contains=keywords))
		elif types == 'username':
			data = Users.objects.filter(username__contains=keywords)
		elif types == 'email':
			data = Users.objects.filter(email__contains=keywords)
		elif types == 'phone':
			data = Users.objects.filter(phone__contains=keywords)
		elif types == 'sex':
			data = Users.objects.filter(sex__contains=keywords)
		elif types == 'age':
			data = Users.objects.filter(age__contains=keywords)
		elif types == 'addtime':
			data = Users.objects.filter(addtime__contains=keywords)
		elif types == 'status':
			data = Users.objects.filter(status__contains=statuslist.get(keywords,'a#s'))
		
		# 过滤逻辑删除掉的数据
		data = data.exclude(status=2)
	else:
		# 没有搜索条件，搜索全部用户信息
		data = Users.objects.exclude(status = 2)


	# 数据分页
	from django.core.paginator import Paginator
	# 实例化分页类 参数1 查询的数据，参数2 每页要显示的数据
	paginator = Paginator(data,5)

	# 当前页码
	p = int(request.GET.get('p',1))

	# 根据当前页码获取当前页码应该显示的数据
	userlist = paginator.page(p)

	# 获取当前页的页码数
	num = paginator.page_range


	# 分配数据
	context = {'uinfo':userlist,'pagenum':num}

	return render(request,'admin/user/list.html',context)

# 更新用户状态

def userstatus(request):
	uid = request.GET['uid']
	status = request.GET['status']
	obj = Users.objects.get(id = uid)
	obj.status = int(status)
	obj.save()
	return HttpResponse('userstatus')


# 用户编辑
@permission_required('myadmin.edit_users',raise_exception = True)
def useredit(request,uid):
	
	obj = Users.objects.get(id=uid)
	context = {'uinfo':obj}
	# 转到编辑页面
	return render(request,'admin/user/edit.html',context)






# 用户更新
@permission_required('myadmin.edit_users',raise_exception = True)
def userupdate(request):
	uid = request.POST.get('uid')
	try:
		obj = Users.objects.get(id = uid)
		obj.username = request.POST.get('username')
		obj.email = request.POST.get('email')
		obj.phone = request.POST.get('phone')
		obj.age = request.POST.get('age')
		obj.sex = request.POST.get('sex')

		# 判断是否有文件上传
		if request.FILES.get('picurl',None):

			if obj.picurl not in ['/static/pics/default/default.ico','/static/pics/default/default.jpg']:
				import os
				# 不是默认头像则删除头像文件
				os.remove('.'+obj.picurl)

			# 上传新的头像
			obj.picurl = upload(request)
		# 执行更新
		obj.save()
		return HttpResponse('<script>alert("修改成功");location.href="/admin/user/list"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/user/edit/'+ str(uid) +'"</script>')
	
	# return HttpResponse('userupdate')



# 用户删除
@permission_required('myadmin.del_users',raise_exception = True)
def userdel(request,uid):
	try:
		# 获取用户要删除的数据
		obj = Users.objects.get(id=uid)
		obj.status = 2
		obj.save()
		return HttpResponse('<script>alert("删除成功");location.href="/admin/user/list"</script>')
	except:
		return HttpResponse('<script>alert("删除失败");location.href="/admin/user/list"</script>')
















def upload(request):
	myfile = request.FILES.get('picurl',None)
	#判断是否有文件上传
	if not myfile:
		# 返回默认头像
		return '/static/pics/default/default.ico'

	# 执行文件上传
	import time,random
	# 头像名称 时间戳+随机数+.+后缀名
	filename = str(time.time())+str(random.randrange(10000,99999))
	# 获取当前文件后缀名
	hzm = myfile.name.split('.').pop()
	# 当前允许上传的后缀名
	arr = ['ico','jpg','jpeg','gif','bmp','png']
	if hzm not in arr:
		return False

	# 打开文件
	file = open('./static/pics/'+filename+'.'+hzm,'wb+')
	# 分块写入文件
	for chunk in myfile.chunks():
		file.write(chunk)
	# 关闭文件
	file.close()

	# 返回文件的url路径
	return '/static/pics/'+filename+'.'+hzm



	# 获取验证码
def getvcode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '1234567890'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')	

